package util;

import org.apache.http.Consts;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Jaxb2工具类
 */
public class JaxbUtil {

    private static final Charset CHARSET = Consts.UTF_8;
//    private static Charset CHARSET = Charset.forName("UTF-8");

    private static final ConcurrentHashMap<Class<?>, JAXBContext> m = new ConcurrentHashMap<Class<?>, JAXBContext>();

    private static JAXBContext getContext(Class<?> clazz) throws JAXBException {
        JAXBContext c = m.get(clazz);
        if (c != null) {
            return c;
        }
        c = JAXBContext.newInstance(clazz);
        JAXBContext e = m.putIfAbsent(clazz, c);
        if (e != null) {
            return e;
        }

        return c;
    }

    /**
     * JavaBean转换成xml
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj) {
        return convertToXml(obj, CHARSET);
    }

    /**
     * JavaBean转换成xml
     *
     * @param obj
     * @return
     */
    public static String convertToXml(Object obj, Charset charset) {
        String result = null;
        JAXBContext context = null;
        Marshaller marshaller = null;
        try {
            context = getContext(obj.getClass());
            marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, charset.name());
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (JAXBException e) {
            throw new RuntimeException("转换对象到XML失败", e);
        }
        return result;
    }

    /**
     * xml转换成JavaBean
     *
     * @param xml
     * @param c
     * @return
     */
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        JAXBContext context = null;
        Unmarshaller unmarshaller = null;
        try {
            context = getContext(c);
            unmarshaller = context.createUnmarshaller();

            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (JAXBException e) {
            throw new RuntimeException("转换XML到对象失败", e);
        }

        return t;
    }

    @XmlRootElement(name = "xml")
    @XmlAccessorType(XmlAccessType.FIELD)
    private static class WrappedMap {
        public WrappedMap() {

        }
    }

}